package mail;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import com.sun.mail.imap.IMAPBodyPart;

import contacts.Owner;

/**
 * Ließt alle Email Daten aus
 * 
 * @author Michi
 * 
 */
public class MimeMessageReader {

	private ArrayList<Address> fromList;
	private String subject;
	private Date sent;
	private Date received;
	private ArrayList<Address> allRecipients;
	private ArrayList<Address> toRecipients;
	private ArrayList<Address> ccRecipients;
	private ArrayList<Address> bccRecipients;
	private ArrayList<File> attachments;
	private String content;
	private String tempPath = "temp/";
	private String textType;

	public MimeMessageReader(Message message) throws IOException,
			MessagingException {

		fromList = new ArrayList<Address>();
		allRecipients = new ArrayList<Address>();
		toRecipients = new ArrayList<Address>();
		ccRecipients = new ArrayList<Address>();
		bccRecipients = new ArrayList<Address>();
		attachments = new ArrayList<File>();

		Address[] fromAddresses = message.getFrom();
		for (int i = 0; i < fromAddresses.length; i++) {
			getFromList().add(fromAddresses[i]);
		}

		setSubject(message.getSubject());
		setSent(message.getSentDate());
		setReceived(message.getReceivedDate());

		Address[] recipientsAll = message.getAllRecipients();
		for (int i = 0; i < recipientsAll.length; i++) {
			getAllRecipients().add(recipientsAll[i]);
		}

		Address[] recipientsTO = message.getRecipients(RecipientType.TO);

		for (int i = 0; i < recipientsTO.length; i++) {
			getToRecipients().add(recipientsTO[i]);
		}

		if (message.getRecipients(RecipientType.CC) != null) {
			Address[] recipientsCC = message.getRecipients(RecipientType.CC);

			for (int i = 0; i < recipientsCC.length; i++) {
				getCcRecipients().add(recipientsCC[i]);
			}
		}

		if (message.getRecipients(RecipientType.BCC) != null) {
			Address[] recipientsBCC = message.getRecipients(RecipientType.BCC);
			for (int i = 0; i < recipientsBCC.length; i++) {
				getBccRecipients().add(recipientsBCC[i]);
			}
		}

		// Inhalt der Email

		if (message.getContent() instanceof Multipart) {
			Multipart multipart = (Multipart) message.getContent();

			for (int i = 0; i < multipart.getCount(); i++) {
				Part part = multipart.getBodyPart(i);

				if (part.getContentType().contains("mixed")) {

				}

				// Setting content
				if (part.getContentType().contains("text/plain")) {
					setContent(part.getContent().toString());
					setTextType("text/plain");

				}

				if (part.getContentType().contains("text/html")) {
					setContent(part.getContent().toString());
					setTextType("text/html");

				}

				if (part.getContentType().contains("multipart/related")) {

					if (part.getContent() instanceof MimeMultipart) {
						MimeMultipart mmp = (MimeMultipart) part.getContent();

						for (int k = 0; k < mmp.getCount(); k++) {
							IMAPBodyPart imp = (IMAPBodyPart) mmp
									.getBodyPart(k);

							if (imp.getContentType().contains("image")
									|| imp.getContentType().contains("video")
									|| imp.getContentType().contains("audio")
									|| imp.getContentType().contains(
											"application")) {

								String fileName = imp.getFileName();
								if (fileName != null) {
									((IMAPBodyPart) imp).saveFile(tempPath
											+ File.separator + fileName);

									attachments.add(new File(tempPath
											+ File.separator + fileName));

								}

							}

							if (imp.getContentType().contains("text/plain")) {
								setContent(imp.getContent().toString());
								setTextType("text/plain");
							}

							if (imp.getContentType().contains("text/html")) {
								setContent(imp.getContent().toString());
								setTextType("text/html");
							}
						}

					}

				}

				if (part.getContentType().contains("multipart/alternative")) {
					if (part.getContent() instanceof MimeMultipart) {
						MimeMultipart mmp = (MimeMultipart) part.getContent();

						for (int k = 0; k < mmp.getCount(); k++) {
							IMAPBodyPart imp = (IMAPBodyPart) mmp
									.getBodyPart(k);

							if (imp.getContentType().contains("text/plain")) {
								setContent(imp.getContent().toString());
								setTextType("text/plain");
							}

							if (imp.getContentType().contains("text/html")) {
								setContent(imp.getContent().toString());
								setTextType("text/html");
							}
						}

					}

				}

				if (part.getContentType().contains("multipart/mixed")) {
					if (part.getContent() instanceof MimeMultipart) {
						MimeMultipart mmp = (MimeMultipart) part.getContent();

						for (int k = 0; k < mmp.getCount(); k++) {
							IMAPBodyPart imp = (IMAPBodyPart) mmp
									.getBodyPart(k);

							if (imp.getContentType().contains("image")
									|| imp.getContentType().contains("video")
									|| imp.getContentType().contains("audio")
									|| imp.getContentType().contains(
											"application")) {

								// ------------
								String fileName = imp.getFileName();
								// byte[] temp = fileName.getBytes();
								//
								// String s = new String(temp, "");

								// __________________

								if (fileName != null) {
									((IMAPBodyPart) imp).saveFile(tempPath
											+ File.separator + fileName);

									attachments.add(new File(tempPath
											+ File.separator + fileName));

								}

							}

							if (imp.getContentType().contains("text/plain")) {
								setContent(imp.getContent().toString());
								setTextType("text/plain");
							}

							if (imp.getContentType().contains("text/html")) {
								setContent(imp.getContent().toString());
								setTextType("text/html");
							}

						}
					}

				}

				// getting attachments
				if (part instanceof MimeBodyPart) {
					@SuppressWarnings("unused")
					MimeBodyPart mbp = (MimeBodyPart) part;

					String fileName = part.getFileName();
					if (fileName != null) {
						((MimeBodyPart) part).saveFile(tempPath
								+ File.separator + fileName);

						attachments.add(new File(tempPath + File.separator
								+ fileName));

					}
					if (fileName == null) {
						if (part.getContent() instanceof String) {
							if ((String) part.getContent() == null) {
								setContent("");
							} else {
								setContent((String) part.getContent());
							}
						}
					}
				}

				// if (part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
				// {
				// String fileName = part.getFileName();
				// ((MimeBodyPart) part).saveFile(tempPath + File.separator
				// + fileName);
				//
				// attachments.add(new File(tempPath + File.separator
				// + fileName));
				//
				// }
			}
		}

		else {
			setContent((String) message.getContent());
			setTextType("text/plain");
		}

		// for later use :)
		// for (int i = 0; i < attachments.size(); i++) {
		// File source = attachments.get(i);
		// File desc = new File("temp2/");
		// try {
		// FileUtils.copyFileToDirectory(source, desc);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// }

	}

	public String messageToString() {
		String str = "From: ";
		for (int i = 0; i < getFromList().size(); i++) {
			if (i < getFromList().size() - 1) {
				str = str + getFromList().get(i) + ",";
			} else {
				str = str + getFromList().get(i) + "\n";
			}
		}

		str = str + "An: ";
		for (int i = 0; i < getToRecipients().size(); i++) {
			if (i < getToRecipients().size() - 1) {
				str = str + getToRecipients().get(i) + ",";
			} else {
				str = str + getToRecipients().get(i) + "\n";
			}
		}

		str = str + "CC: ";
		if (getCcRecipients().isEmpty()) {
			str = str + "\n";
		}
		for (int i = 0; i < getCcRecipients().size(); i++) {
			if (i < getCcRecipients().size() - 1) {
				str = str + getCcRecipients().get(i) + ",";
			} else {
				str = str + getCcRecipients().get(i) + "\n";
			}
		}

		// test ob ueberhaupt moeglich

		str = str + "BCC:";

		if (getBccRecipients().isEmpty()) {
			str = str + "\n";
		}

		for (int i = 0; i < getBccRecipients().size(); i++) {
			if (i < getBccRecipients().size() - 1) {
				str = str + getBccRecipients().get(i) + ",";
			} else {
				str = str + getBccRecipients().get(i) + "\n";
			}
		}

		str = str + "Betreff: " + getSubject() + "\n";

		str = str + "Gesendet am: " + getSent().toString() + "\n";

		str = str + "Empfangen am: " + getReceived().toString() + "\n";

		str = str + "Inhalt: " + "\n" + getContent() + "\n";

		str = str + "Attachments: " + "\n";

		for (int i = 0; i < attachments.size(); i++) {
			str = str + attachments.get(i) + "\n";

		}

		return str;
	}

	public ArrayList<Address> getFromList() {
		return fromList;
	}

	public void setFromList(ArrayList<Address> fromList) {
		this.fromList = fromList;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public Date getSent() {
		return sent;
	}

	public void setSent(Date sent) {
		this.sent = sent;
	}

	public Date getReceived() {
		return received;
	}

	public void setReceived(Date received) {
		this.received = received;
	}

	public ArrayList<Address> getAllRecipients() {
		return allRecipients;
	}

	public void setAllRecipients(ArrayList<Address> allRecipients) {
		this.allRecipients = allRecipients;
	}

	public ArrayList<Address> getToRecipients() {
		return toRecipients;
	}

	public void setToRecipients(ArrayList<Address> toRecipients) {
		this.toRecipients = toRecipients;
	}

	public ArrayList<Address> getCcRecipients() {
		return ccRecipients;
	}

	public void setCcRecipients(ArrayList<Address> ccRecipients) {
		this.ccRecipients = ccRecipients;
	}

	public ArrayList<Address> getBccRecipients() {
		return bccRecipients;
	}

	public void setBccRecipients(ArrayList<Address> bccRecipients) {
		this.bccRecipients = bccRecipients;
	}

	public ArrayList<File> getAttachments() {
		return attachments;
	}

	public void setAttachments(ArrayList<File> attachments) {
		this.attachments = attachments;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getTempPath() {
		return tempPath;
	}

	public void setTempPath(String tempPath) {
		this.tempPath = tempPath;
	}

	public static void main(String[] args) {
		Owner owner = new Owner("", "");
		owner = new Owner("Michael", "Brandt");
		owner.setEmail("testmail@brotek.eu");
		owner.setImapServer("imap.brotek.eu");
		owner.setMailPass("test123");
		owner.setSmtpServer("smtp.brotek.eu");
		owner.setProvider("imap");

		MyModelEmail mme = new MyModelEmail();
		mme.listInbox();

	}

	public String getTextType() {
		return textType;
	}

	public void setTextType(String textType) {
		this.textType = textType;
	}
}
